package io.renren.common.utils;

import io.renren.modules.noc.dao.NocMemberDao;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.LinkedList;
import java.util.ListIterator;
import java.util.Map;
/**
 * @Author wangfj
 * @Description //TODO 生成用户唯一二维码
 * @Date 11:28 2019/7/25 0025
 * @Param
 * @return
 **/

@Component
public class MemberQRCodeUtil {
    @Autowired
    private NocMemberDao nocMemberDao;
    public static LinkedList<Integer> linkedList = new LinkedList<Integer>();

    /**
     * @Author wangfj
     * @Description //TODO 生成二维码
     * @Date 11:28 2019/7/25 0025
     * @Param [machineCode]
     * @return java.lang.String
     **/

    public synchronized  String getMemberQRCode(String machineCode){
        System.out.println("拿到锁锁定此对象");
        StringBuffer qrCode = new StringBuffer();
        String rQrcode = null;
        //初始化linkedList--从数据库查出最大的二维码序列循环加一并插入到linkedList
         if(linkedList.size()==0){
            this.setLinkedList(machineCode);
        }
         //如果队列中
         if(linkedList.size()<=50){
             this.addLinkedList();
         }
        Integer nQrCode = linkedList.pollFirst();//获取队列中第一个二维码
        qrCode.append(nQrCode.toString());
         while(qrCode.length()<6){
             qrCode.insert(0,"0");
         }
         rQrcode = qrCode.insert(0, machineCode).toString();
         System.out.println("拿到的二维码："+qrCode);
         System.out.println("执行完释放锁");
        return rQrcode;
    }
    public  void setLinkedList(String machineCode){
        Map<String, String> qrMap = nocMemberDao.getMemberQRCode(machineCode);
        String oQrCode = qrMap.get("qrCode");
        if(StringUtils.isEmpty(oQrCode)){
            oQrCode = "0";
        }
        Integer icode = Integer.parseInt(oQrCode);
        for(int i = 0;i<=100;i++){
            linkedList.add(++icode);
        }
    }
    public void addLinkedList(){
        Integer last = linkedList.getLast();
        for(int i = 0;i<=100;i++){
            linkedList.add(++last);
        }
    }
}
